<?php

namespace App\Logging\Logger;

use App\Logging\Service\LogCmdService;
use App\Logging\Service\LogJobService;
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class JobLogger
{
    protected $name = 'job';

    /**
     * Create a custom Monolog instance.
     *
     * @param  array  $config
     * @return \Monolog\Logger
     */
    public function __invoke(array $config)
    {
        $logger = new Logger($this->name);

        // 根据命令名称生成日志目录，所以需要在命令执行时传入命令相关信息
        $subDir = LogJobService::getInstance()->generateJobLogSubDir($config['path_mode']);
        if ($subDir) {
            $oldDir = dirname($config['path']);
            $newDir = $oldDir . '/' . $subDir;
            $path = str_replace($oldDir, $newDir, $config['path']);
        }
        else {
            $path = $config['path'];
        }

        // 添加 handler
        $handler = new RotatingFileHandler($path, $config['days'], $config['level']);
        $handler->setFormatter(new JsonFormatter());
        $logger->pushHandler($handler);

        $errorHandler = new RotatingFileHandler($config['path_error'], $config['days'], 'error');
        $errorHandler->setFormatter(new JsonFormatter());
        $logger->pushHandler($errorHandler);

        // 添加 processor
        if (isset($config['processor'])) {
            foreach ($config['processor'] as $processor) {
                $logger->pushProcessor(new $processor);
            }
        }

        return $logger;
    }
}
